var express = require('express');
var router = express.Router();
var qr = require('qr-image');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express', images: uploadedImages});
  // res.end();
});

router.get('/photo/:photoid', function(req, res, next){
	res.render('photo', { title: 'Photo Detail', photoid: req.params.photoid });
})

//generates transparent image when user selects it
router.post('/photo/transparent/:photoid', function(req, res, next){
  var base64Data = req.body.imgBase64.replace(/^data:image\/png;base64,/, "");
  require('fs').writeFile('./public/images/trans/' + req.params.photoid, base64Data, 'base64', function(err){
    console.log(err);
  })
  res.send('images/trans/' + req.params.photoid)
})

//exports data from canvas when user saves image
router.post('/photo/:photoid', function(req, res, next){
  //save image upload to filesystem
  var base64Data = req.body.imgBase64.replace(/^data:image\/png;base64,/, "");
  require("fs").writeFile('./public/images/final/'+req.params.photoid +'.png', base64Data, 'base64', function(err) {
    console.log(err);
  });
  //generate new qr code and send back route

  // **SET THE QR ROUTE BELOW AS AN ABSOLUTE ROUTE TO THE PRODUCTION SERVER **
  
  var qr_png = qr.image('http://greenscreen.shanghaiappmaker.com/myphoto/'+ req.params.photoid, { type: 'png' });
  console.log(qr_png);
  var stream = qr_png.pipe(require('fs').createWriteStream('./public/images/qr/' + req.params.photoid + '.png'));
  stream.on('finish', function(){
    res.send({qrpath: 'images/qr/' + req.params.photoid});
  })
})

router.get('/myphoto/:resultid', function(req, res, next){
  res.render('result', {title: 'My Photo', resultid: req.params.resultid})
})


// NEW ROUTES FOR API BACKEND

router.get('/api/photos/:userphonenumber', function(req, res, next){
  res.send(req.params.userphonenumber);
})




module.exports = router;



//custom javascript
var chokidar = require('chokidar');

var watcher = chokidar.watch('public/images/uploads/', {ignored: /^\./, persistent: true});

watcher
  .on('add', function(path) {
    console.log('File', path, 'has been added');
    var pathMod = path.substring(6);
    uploadedImages.push(pathMod);
  })
  .on('change', function(path) {
    console.log('File', path, 'has been changed');
  })
  .on('unlink', function(path) {
    console.log('File', path, 'has been removed');
    var pathMod = path.substring(6);
    helperRemoveImage(pathMod);
  })
  .on('error', function(error) {
    console.error('Error occurred', error);
  })

var uploadedImages = [];

var helperRemoveImage = function(target){
  var index = uploadedImages.indexOf(target);
  if( index > -1) {
    uploadedImages.splice(index, 1);
  } 
}